<template>
    <el-card shadow="never">
        <store-progress v-model="step" :progress="progress" :type="2" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="9" />
            </div>
            <div class="line"></div>
            <div v-show="step === 1" class="msg zw-common-scrollbar">
                <div class="title">
                    <span class="text">购买订单/商品同步服务</span>
                    <el-button type="primary" size="small" :disabled="disabledFunc" @click="letsGo"> 去购买 </el-button>
                </div>
                <div class="sync">
                    <div class="sync-title">请点击“去购买”，前往视频号小店服务市场购买用用。</div>
                    <div class="sync-img">
                        <!-- 购买图片后续会随时更换，暂用这张图 -->
                        <el-image
                            src="//static.scrm.keyid.cn/assets/images/web-pc/buy.png"
                            draggable="false"
                            fit="cover">
                            <template #error>
                                <div class="image-slot">
                                    <el-icon><icon-picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                    </div>
                </div>
                <div class="title">
                    <span class="text">店铺基本信息</span>
                </div>
                <el-form
                    ref="storeBaseFormRef"
                    :model="storeBaseForm"
                    :rules="storeBaseFormRules"
                    label-width="auto"
                    :disabled="disabledFunc">
                    <el-form-item v-if="disabledFunc" label="客易达店铺ID" disabled required>
                        <el-input v-model="shop_id"></el-input>
                    </el-form-item>
                    <el-form-item label="视频号小店ID" prop="external_shop_id">
                        <div class="withTips">
                            <el-input
                                v-model.trim="storeBaseForm.external_shop_id"
                                placeholder="请输入视频号小店ID"
                                @keydown.enter="inputShopIdHandle">
                                <template #suffix>
                                    <div class="search-shop-icon">
                                        <el-icon size="18"><Search /></el-icon>
                                    </div>
                                </template>
                            </el-input>
                            <span @click="handleLookVideoNum">如何查看视频号小店ID</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="name">
                        <identify-name v-model="storeBaseForm.name" />
                    </el-form-item>
                    <el-form-item label="店铺logo" prop="logo">
                        <identify-logo v-model="storeBaseForm.logo" />
                    </el-form-item>
                    <el-form-item label=" " prop="order_sync">
                        <el-checkbox
                            v-model="storeBaseForm.order_sync"
                            true-label="1"
                            false-label="2"
                            label="同步历史订单" />
                        <div v-show="storeBaseForm.order_sync === '1'" class="sync_day">
                            同步历史<el-input-number
                                v-model="storeBaseForm.sync_day"
                                :min="1"
                                :max="365"
                                :controls="false"
                                placeholder="请输入" />天（不超过365天）内的视频号小店订单
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            <div v-show="step === 2" class="finishBox">
                <el-icon size="60px" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">店铺创建成功</div>
                <div class="tag">您的客易达店铺ID为：{{ shop_id }} <span @click="copy(shop_id)">复制</span></div>
            </div>
        </div>
    </el-card>
    <div class="footer_button">
        <el-button v-if="step === 1" :loading="loading" type="primary" @click="nextStep"> 下一步 </el-button>
        <el-button v-if="step === 2" type="primary" @click="done"> 完成 </el-button>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
import { get } from 'lodash';
import { creatWxVshop, getWxVshopInfo, getStoreDetail } from '@/api/ecommerce/storeManage';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import identifyName from '../components/identifyName.vue';
import identifyLogo from '../components/identifyLogo.vue';

import useClipboard from 'vue-clipboard3';

import type { FormInstance, FormRules } from 'element-plus';

const routers = useRoute();
const { toClipboard } = useClipboard();
const { type } = routers.query;

const storeBaseFormRef = ref<FormInstance>();

/* ----------------------------店铺授权-start---------------------------- */
const shop_id = ref<string>('');
const loading = ref<boolean>(false);
type storeBaseFormProp = {
    external_shop_id: string;
    name: string;
    logo: string;
    order_sync: string; // 同步历史订单
    sync_day?: number; // 同步天数
};
const storeBaseForm = reactive<storeBaseFormProp>({
    external_shop_id: '',
    name: '',
    logo: '',
    order_sync: '2',
    sync_day: undefined
});
/**
 * 是否禁用表单
 */
const disabledFunc = computed(() => {
    return type == 'look';
});

/**
 * 获取店铺详情
 */
const getStoreDetails = async () => {
    const data = await getStoreDetail({ retail_shop_id: routers.query.shop_id });
    const { external_shop_id, name, logo, retail_shop_id, retail_shop_config } = data;
    storeBaseForm.external_shop_id = external_shop_id;
    storeBaseForm.name = name;
    storeBaseForm.logo = logo;
    const retail_shop_config_data = retail_shop_config;
    const { sync_day, order_sync } = retail_shop_config;
    storeBaseForm.order_sync = order_sync ? order_sync.toString() : order_sync;
    storeBaseForm.sync_day = sync_day;
    shop_id.value = retail_shop_id;
};

onMounted(() => {
    const shop_id: any = routers.query.shop_id;
    if (!shop_id) return;
    if (type == 'look') {
        getStoreDetails();
        return;
    }

    storeBaseForm.external_shop_id = shop_id;
    storeBaseFormRef.value!.validate();
});

const inputShopIdHandle = () => {
    storeBaseFormRef.value!.validate();
};

const setBaseFormValue = (name = '', logo = '') => {
    storeBaseForm.name = name;
    storeBaseForm.logo = logo;
    storeBaseFormRef.value!.validateField('name');
    storeBaseFormRef.value!.validateField('logo');
};

const validateID: any = async (rule: any, value: any, callback: any) => {
    if (!value) {
        setBaseFormValue();
        callback(new Error('请输入视频号小店ID'));
    } else {
        try {
            loading.value = true;
            storeBaseForm.name = storeBaseForm.name || '获取中...';
            const params = { external_shop_id: value };
            const { nickname: name, headimg_url: logo } = await getWxVshopInfo(params);
            setBaseFormValue(name, logo);
            callback();
        } catch (err) {
            setBaseFormValue();
            const msg: string = get(err, 'msg', err);
            callback(new Error(msg));
        } finally {
            loading.value = false;
        }
    }
};

const syncValidate: any = async (rule: any, value: any, callback: any) => {
    if (value === '2') {
        return callback();
    }
    if (!storeBaseForm.sync_day) {
        return callback(new Error('需要设置同步历史天数'));
    }
    callback();
};

const storeBaseFormRules = reactive<FormRules>({
    external_shop_id: [{ required: true, validator: validateID, trigger: 'blur' }],
    name: [{ required: true, message: '请输入视频号小店ID', trigger: 'change' }],
    logo: [{ required: true, message: '请输入视频号小店ID', trigger: 'change' }],
    order_sync: [{ validator: syncValidate, trigger: 'blur' }]
});

const letsGo = () => {
    window.open('//channels.weixin.qq.com/shop', '_blank');
};
/* ----------------------------店铺授权-end---------------------------- */

/* ----------------------------查看视频号id-start---------------------------- */
const handleLookVideoNum = () => {
    window.open(`${location.origin}/look-viedo-num`, '_blank');
};
/* ----------------------------查看视频号id-end---------------------------- */

const creatWxVshopCom = async (): Promise<boolean> => {
    const params = {
        ...storeBaseForm,
        source: 9
    };
    const res = await creatWxVshop(params);
    shop_id.value = `${res?.shop_id}`;
    return !!`${res?.shop_id}`;
};

const copy = async (val: string) => {
    try {
        await toClipboard(val);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

/* ----------------------------步骤条-start---------------------------- */
const step = ref<number>(1);
const progress = ref<any>(['店铺授权', '完成']);

const nextStep = async (): Promise<void> => {
    if (type == 'look') {
        if (step.value < 2) step.value++;
        return;
    }
    if (!storeBaseFormRef.value) return;
    await storeBaseFormRef.value.validate(async (valid: any): Promise<void> => {
        if (!valid) return;
        const result = await creatWxVshopCom();
        if (result) {
            if (step.value < 2) step.value++;
        }
    });
};

const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};
/* ----------------------------步骤条-end---------------------------- */
</script>
<style scoped lang="scss">
@import './index';
</style>
